package com.pine.app.module.security.core.authorize.decisions;

import com.pine.app.module.security.core.authorize.metadataSource.ConfigAttribute;
import com.pine.app.module.security.core.common.SpringContextUtils;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author xiaoyuan
 * @create 2020/3/23 22:27
 **/
@Slf4j
public class AuthorizeDecisionHanler {

    private static Map<String, AuthorizeDecision> authorizeDecisionMap;


    public AuthorizeDecisionHanler() {
        if (authorizeDecisionMap == null || authorizeDecisionMap.size() == 0) {
            Collection<AuthorizeDecision> authenticators = Collections.emptyList();
            //获取oauth的请求的校验接口所有实现类
            Map<String, AuthorizeDecision> integrationAuthenticatorMap = SpringContextUtils.getBeanMap(AuthorizeDecision.class);
            if (integrationAuthenticatorMap != null) {
                authenticators = integrationAuthenticatorMap.values();
            }
            authorizeDecisionMap = authenticators.stream().collect(Collectors.toMap(v -> v.getType(), v -> v));
        }
    }

    public boolean decide(String type, List<ConfigAttribute> list, HttpServletRequest request, String... target) {
        if (authorizeDecisionMap == null || authorizeDecisionMap.size() == 0) {
            log.error("权限校验器未初始化成功");
            return true;
        }
        AuthorizeDecision authorizeDecision = authorizeDecisionMap.get(type);
        if (authorizeDecision == null) {
            log.warn("不支持此权限类型（" + type + "）");
            return true;
        }
        return authorizeDecision.decide(list, request,target);
    }
}
